import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { getInfo, login, getRouterList, logout } from '@/api/user'
import defaultSettings from '@/settings'
const { avatarUrl } = defaultSettings

const state = {
  token: getToken(),
  name: '',
  realName: '',
  avatar: '',
  introduction: '',
  roles: [],
  routerList: [],
  isRegister: false
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_REAL_NAME: (state, realName) => {
    state.realName = realName
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles.push(roles)
  },
  RESET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROUTER: (state, routerList) => {
    state.routerList = routerList
  },
  SET_IS_REGISTER: (state, isRegister) => {
    state.isRegister = isRegister
  }
}

const actions = {
  // 用户登录
  login({ commit, dispatch }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        commit('SET_TOKEN', response.data.token)
        dispatch('getInfo')
        setToken(response.data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response
        if (!data) {
          reject('获取用户信息失败，请重新登录.')
        }

        // 存用户信息
        const avatar = avatarUrl + data.avatar
        commit('SET_ROLES', data.roleCode)
        commit('SET_REAL_NAME', data.realName)
        commit('SET_NAME', data.username)
        commit('SET_AVATAR', avatar)

        resolve(avatar)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 动态获取路由列表
  getRouterList({ commit }) {
    return new Promise((resolve, reject) => {
      getRouterList().then(response => {
        const { data } = response
        if (!data) {
          reject('获取用户路由表为空，请联系管理员！')
        }
        commit('SET_ROUTER', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户退出登录
  logout({ dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(async() => {
        await dispatch('resetToken')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 删除 token
  resetToken({ commit, dispatch }) {
    return new Promise(resolve => {
      // 清除token、username、realNamr、cookie中的token
      commit('SET_ROUTER', [])
      commit('SET_TOKEN', '')
      commit('SET_NAME', '')
      commit('SET_REAL_NAME', '')
      commit('SET_AVATAR', '')
      // commit('SET_AVATAR', '')
      // 清除路由信息
      commit('RESET_ROLES', [])
      dispatch('permission/resetRoutes', null, { root: true })
      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })
      resetRouter()
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
